package com.spontaneappnew.activities;

import java.util.ArrayList;

import android.content.Intent;
import android.location.Location;
import android.os.Bundle;

import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.spontaneappnew.Categories;
import com.spontaneappnew.Categories_Places;
import com.spontaneappnew.NavDrawerActivityConfiguration;
import com.spontaneappnew.NavDrawerItem;
import com.spontaneappnew.NavMenuFBHeader;
import com.spontaneappnew.NavMenuItem;
import com.spontaneappnew.Place;
import com.spontaneappnew.Places;
import com.spontaneappnew.R;
import com.spontaneappnew.adapters.CustomInfoWindowAdapter;
import com.spontaneappnew.adapters.NavDrawerAdapter;

public class MapActivity extends AbstractNavDrawerActivity implements LocationListener{
	
	private GoogleMap map;

	// Global variable to hold the current location
    private Location mCurrentLocation;
    // Define an object that holds accuracy, frequency and number of updates parameters
    private LocationRequest mLocationRequest;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		  super.onCreate(savedInstanceState);
	
	      mLocationRequest = LocationRequest.create();
	      // Use high accuracy
	      mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
	      mLocationRequest.setInterval(5000);
	      // Set the request for only one updates
	      mLocationRequest.setNumUpdates(1);
	      
	      if(servicesConnected() && isLocationServicesAvailable){
	    	  mLocationClient.connect();
	      }
	      
		  map = ((MapFragment)getFragmentManager().findFragmentById(R.id.activity_map_container)).getMap();
		  
		  // Show the "get camera to my location" button on the map
		  map.setMyLocationEnabled(true);
		  // Add the relevant markers to the map
		  addMarkersToMap();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if(!mLocationClient.isConnected()){
			// Check if the Google Play Services are available, if not a dialog pops up 
			if(servicesConnected() && isLocationServicesAvailable){
				// Connect the client.
		        mLocationClient.connect();
			}
		}
	}

	@Override
	protected void onPause() {
		// If the client is connected
        if (mLocationClient.isConnected()){
            // Remove location updates for a listener.
            // The current Activity is the listener, so the argument is "this".
        	mLocationClient.removeLocationUpdates(this);
			// Disconnecting the client invalidates it.
	        mLocationClient.disconnect();
        }
		super.onPause();
	}
	
	@Override
	public void onConnected(Bundle bundle) {
		mCurrentLocation = mLocationClient.getLastLocation();
		if(mCurrentLocation != null){
			changeCameraLocationAndZoom();
		}
		// Make an update request for one accurate current location
 		mLocationClient.requestLocationUpdates(mLocationRequest, this);
	}

	@Override
	public void onDisconnected() {}
	
	@Override
	public void onLocationChanged(Location newLocation) {
		mCurrentLocation = mLocationClient.getLastLocation();
        // Move the map's camera to user's location
		changeCameraLocationAndZoom();
	}
	
	private void changeCameraLocationAndZoom(){
		LatLng currLatLng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
        // Update the map fragment's camera to the user's location
        CameraUpdate center = CameraUpdateFactory.newLatLngZoom(currLatLng, 16);
        map.animateCamera(center);
	}
	
	private void addMarkersToMap(){
		CustomInfoWindowAdapter adapter = new CustomInfoWindowAdapter(MapActivity.this);
		Categories categories = Categories.getInstance();
		int isFilteredView = getIntent().getIntExtra("FilteredView", 0);
		final Places places = Places.getInstance();
		map.clear();
		map.setInfoWindowAdapter(adapter);
		if (isFilteredView==0){
			MarkerOptions marker = new MarkerOptions();
			for (Place place : places.getAllPlaces()) {
				LatLng loc = new LatLng(place.getLocation().getLatitude(), place.getLocation().getLongitude());
				marker.position(loc);
				marker.title(place.getId());
				marker.icon(BitmapDescriptorFactory.fromBitmap(categories.getCategoryById(place.getCategory()).getMarker()));
				map.addMarker(marker);
				map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
				
				@Override
				public void onInfoWindowClick(Marker mark) {
					String title = mark.getTitle();
					int index = 0;
					for (Place place : places.getAllPlaces()){
						if (place.getId().compareTo(title)==0){
							index = places.getAllPlaces().indexOf(place);
							break;
						}
					}
					Intent intent = new Intent(MapActivity.this,PlaceProfileActivity.class);
					Places.getInstance().setCurrentPlace(index,1);
				    startActivity(intent);	
				    overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
				}
			});
				
			}
	    } 
	    else {
	    	ArrayList<Categories_Places> placesCats = Places.getInstance().getFilteredPlaces();
	    	for (Categories_Places currCat : placesCats){
		    	MarkerOptions marker = new MarkerOptions();
		    	for (Place place : currCat.getPlaceList()){
	    			LatLng loc = new LatLng(place.getLocation().getLatitude(), place.getLocation().getLongitude());
					marker.position(loc);
					marker.title(place.getId());
					marker.icon(BitmapDescriptorFactory.fromBitmap(categories.getCategoryById(place.getCategory()).getMarker()));
					map.addMarker(marker);
					map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
						
						@Override
						public void onInfoWindowClick(Marker mark) {
							String title = mark.getTitle();
							int index = 0;
							for (Place place : places.getAllPlaces()){
								if (place.getId().compareTo(title)==0){
									index = places.getAllPlaces().indexOf(place);
									break;
								}
							}
							Intent intent = new Intent(MapActivity.this,PlaceProfileActivity.class);
							Places.getInstance().setCurrentPlace(index,1);
						    startActivity(intent);	
						    overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
						}
					});
		    	}	
	    	}
	    		
	    }
	}
	
	///////////////////////// NAV DRAWER ////////////////////////////////////////////
	
	@Override
    protected void onNavItemSelected(int id) {
		Intent intent = null;
        switch ((int)id) {
        // Home nav button was pressed - no need to act
        case 101:
        	intent = new Intent(this, HomeActivity.class);
            break;
        // My places nav drawer was pressed
        case 102:
        	intent = new Intent(this, MyPlacesNew.class);
        	break;
        // Settings nav button was pressed
        case 103:
            intent = new Intent(this, SettingsActivity.class);
            break;
	    }
        if(intent != null)
        	startActivity(intent);
        else
        	super.onNavItemSelected(id);
    }

	@Override
	protected NavDrawerActivityConfiguration getNavDrawerConfiguration() {
		NavDrawerItem[] menu = new NavDrawerItem[] {
        		NavMenuFBHeader.create( 100, "User"),
                NavMenuItem.create(101, "Home", "ic_home", this),
                NavMenuItem.create(102, "My Places", "ic_menu_myplaces", this),
                NavMenuItem.create(103, "Settings", "ic_menu_settings", this),
                NavMenuItem.create(105, "About", "ic_action_about_light", this),
                NavMenuItem.create(107, "Rate Us!", "ic_whats_hot", this),
                NavMenuItem.create(108, "Logout", "ic_menu_logout", this)};
        
        NavDrawerActivityConfiguration navDrawerActivityConfiguration = new NavDrawerActivityConfiguration();
        navDrawerActivityConfiguration.setMainLayout(R.layout.activity_map);
        navDrawerActivityConfiguration.setDrawerLayoutId(R.id.drawer_layout);
        navDrawerActivityConfiguration.setLeftDrawerId(R.id.left_drawer);
        navDrawerActivityConfiguration.setNavItems(menu);
        navDrawerActivityConfiguration.setDrawerShadow(R.drawable.drawer_shadow);       
        navDrawerActivityConfiguration.setDrawerOpenDesc(R.string.drawer_open);
        navDrawerActivityConfiguration.setDrawerCloseDesc(R.string.drawer_close);
        navDrawerActivityConfiguration.setBaseAdapter(
            new NavDrawerAdapter(this, R.layout.navdrawer_item, menu ));
        return navDrawerActivityConfiguration;
	}
	
}
